package org.pp.store;

import cn.hutool.core.util.StrUtil;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.pp.core.BizExcept;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Component
@Slf4j
public class QiniuOssStore implements OssStore{

	@Value(value = "${oss.qiniu.key}")
    private String qiniuKey;

    @Value(value = "${oss.qiniu.domain}")
    private String domain;

    @Value(value = "${oss.qiniu.secret}")
    private String qiniuSecret;

    @Value(value = "${oss.qiniu.bucket}")
    private String qiniuBucket;
	
	private Auth auth;

    private UploadManager uploadManager;


    @PostConstruct
    public void init() {
        auth = Auth.create(qiniuKey, qiniuSecret);
        //https://developer.qiniu.com/kodo/1671/region-endpoint-fq
        Configuration cfg = new Configuration(Region.region0());//华东-浙江
        uploadManager = new UploadManager(cfg);
    }


    @Override
    public void upload(MultipartFile file, String storePath) {
        String token = auth.uploadToken(qiniuBucket);
        try {
            uploadManager.put(file.getBytes(), storePath, token);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw BizExcept.erro("上传七牛云失败");
        }
    }
    
    @Override
    public void upload(byte[] bytes, String storePath) {
        String token = auth.uploadToken(qiniuBucket);
        try {
            uploadManager.put(bytes, storePath, token);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw BizExcept.erro("上传七牛云失败");
        }
    }

    @Override
    public String getUrl(String path) {
        if(StrUtil.isBlank(path)){
            return path;
        }
        return this.domain+"/"+path;
    }
}